﻿using System;
using System.Net;
using System.IO;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Xml;

namespace StoneShare.Harvest.AddIn
{
    public class HarvestHelper
    {

        public static bool Validator (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) 
        {     
            return true;   
        }   
        
        public XmlDocument GetMyProjects()   
        {      
            HttpWebRequest request;       
            HttpWebResponse response = null;       
            StreamReader reader;       
       
            
            // Set some variables specific to your account.      
            string uri = Properties.Settings.Default.uri + "/daily/" + DateTime.Now.DayOfYear + "/" + DateTime.Now.Year; 
            string usernamePassword = Properties.Settings.Default.userName  + ":" + Properties.Settings.Default.password;      
            ServicePointManager.ServerCertificateValidationCallback = Validator;      
            try      
            {          
                request = WebRequest.Create(uri) as HttpWebRequest;          
                request.MaximumAutomaticRedirections = 1;         
                request.AllowAutoRedirect = true;         
                // It's important that both the Accept and ContentType headers are         
                // set in order for this to be interpreted as an API request.         
                request.Accept = "application/xml";          
                request.ContentType = "application/xml";
                request.UserAgent = "Outlook";

                // Add the Basic Authentication header with username/password string.         
                request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));         
                using (response = request.GetResponse() as HttpWebResponse)          
                {
                    if (request.HaveResponse == true && response != null)
                    {
                        reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(reader.ReadToEnd());
                        return doc;

                    }
                    else
                        return null;
                }       
            }       
            catch (WebException wex)       
            {          
                if (wex.Response != null)          
                {             
                    using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)             
                    {
                        System.Windows.Forms.MessageBox.Show(String.Format("The server returned '{0}' with the status code {1} ({2:d}).", errorResponse.StatusDescription, errorResponse.StatusCode, errorResponse.StatusCode));             
                    }          
                } 
                else 
                {
                    System.Windows.Forms.MessageBox.Show(wex.Message);
                }
                return null;
            } 
            finally 
            {          
                if (response != null) 
                { 
                    response.Close(); 
                }
          
            }   
        }

        public void SubmitEntry(string projectID, string hours)
        {
            HttpWebRequest request;
            HttpWebResponse response = null;
            StreamReader reader; 

            //Set some variables specific to your account.      
            string uri = Properties.Settings.Default.uri +  "/daily/add";
            string usernamePassword = Properties.Settings.Default.userName + ":" + Properties.Settings.Default.password;
            ServicePointManager.ServerCertificateValidationCallback = Validator;
            try
            {
                request = WebRequest.Create(uri) as HttpWebRequest;
                request.MaximumAutomaticRedirections = 1;
                request.AllowAutoRedirect = true;        
                request.Accept = "application/xml";
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = "Outlook";

                //Add the Basic Authentication header with username/password string.         
                request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));

                request.Method = "POST";

                byte[] postData;
                string postString;
                postString = CreateEntryXML(projectID, hours);

                postData = Encoding.UTF8.GetBytes(postString); 
                request.ContentLength = postData.Length;
                Stream PostData = request.GetRequestStream();
                PostData.Write(postData, 0, postData.Length);      
      
                PostData.Close();       

                ////Get the response handle, we have no true response yet      
                using (response = request.GetResponse() as HttpWebResponse)
                {
                    if (request.HaveResponse == true && response != null)
                    {
                        reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                        XmlDocument doc = new XmlDocument();
                        System.Net.HttpStatusCode sc = response.StatusCode;
                        if (sc.ToString().ToUpper() == "CREATED")
                        {
                            System.Windows.Forms.MessageBox.Show("Status Code: Created Your time has been added to Harvest");
                        }
                        else
                        {
                            System.Windows.Forms.MessageBox.Show(String.Format("An error occurred trying to save your time to Harvest"));
                        }
                    }
                } 

            }
            catch (WebException wex)
            {
                if (wex.Response != null)
                {
                    using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
                    {
                        System.Windows.Forms.MessageBox.Show(String.Format("The server returned '{0}' with the status code {1} ({2:d}).", errorResponse.StatusDescription, errorResponse.StatusCode, errorResponse.StatusCode));
                    }
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show(wex.Message);
                }
               
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }

            }
        }

        private string CreateEntryXML(string projectID, string hours)
        {
            XmlDocument doc = new XmlDocument ();
            string dte = System.DateTime.Now.ToString("ddd, dd MMM yyyy"); //Expected format: Tue, 21 Feb 2012
            StringBuilder sb = new StringBuilder ();
            sb.Append ("<request>");
            sb.Append ("<notes>Outlook Add-in time submit</notes>");
            sb.Append ("<hours>" + hours + "</hours>");
            sb.Append ("<project_id type=\"integer\">" + projectID + "</project_id>");
            sb.Append ("<task_id type=\"integer\">14</task_id>");
            sb.Append ("<spent_at type=\"date\">" + dte + "</spent_at>");
            sb.Append ("</request>");
            return sb.ToString();


        }
    }
}
